package com.dayatang.product.webapp.action.mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.dayatang.product.domain.Attachment;
import com.dayatang.product.webapp.action.BaseAction;

public class AttachmentBaseAction extends BaseAction {

	private static final long serialVersionUID = 2215345765580088631L;

	public Set<Attachment> uploadFiles(String uploadToDir, List<File> files, List<String> filesFileName) {
		Set<Attachment> attachments = new HashSet<Attachment>();
		for (File file : files) {
			String fileName = filesFileName.get(files.indexOf(file));
			writeFile(file,fileName,uploadToDir);
			Attachment attachment = new Attachment();
			attachment.setFileName(fileName);
			attachment.setSize(file.length()/1024);
			attachment.setCreated(new Date());
			attachment.setPath(uploadToDir + fileName);
			productApplication.saveEntity(attachment);
			attachments.add(attachment);
		}
		return attachments;
	}
	
	private void writeFile(File file, String fileName, String dir) {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(file);
			File uploadFile = new File(dir, fileName);
			if (!uploadFile.getParentFile().exists()) {
				uploadFile.getParentFile().mkdirs();
			}
			os = new FileOutputStream(uploadFile);
			int length = 0;
			byte buffer[] = new byte[1024];
			while ((length = is.read(buffer)) != -1) {
				os.write(buffer, 0, length);
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			closeFileStream(is,os);
		}
	}
	
	public void closeFileStream(InputStream is, OutputStream os) {
		try {
			if (os != null) {
				os.close();
			}
			if (is != null) {
				is.close();
			}
			os = null;
			is = null;
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
